﻿var YorkinPage = {};
YorkinPage.InitializePage = function (elems) {
    var myeventID = parseInt($.url().param('eventID')),
        selectedGuest = null;
    var selectedRecord = null;
    var selectedGiftRecord = null;
    var guestTableData = [];
    var CurrencyHash = elems.CurrencyHash;
   
    function UpdatePageAfterChange() {
        $("#" + elems.GuestsTable).jtable('load', { eventID: myeventID });
        //Event details update
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "Services/EventsService.asmx/GetEventReport",
            data: JSON.stringify({ eventID: myeventID }),
            success: function (response) {
                response = JSON.parse(response.d);
                $("#" + elems.totalGuestsInvited).fadeOut(500, function() {
                    $(this).text(response.TotalGuestsInvited).fadeIn(500);
                });
                $("#" + elems.totalGuestsComing).fadeOut(500, function () {
                    $(this).text(response.TotalGuestsComing).fadeIn(500);
                });
                $("#" + elems.totalGuestsRSVPd).fadeOut(500, function () {
                    $(this).text(response.TotalGuestsRSVPd).fadeIn(500);
                });
            },
            error: function() {
                console.log('error');
            }
        });
    }

    function InitializeRSVPModal(record) {
        selectedRecord = record;
        $("#" + elems.rsvpCheckBox)[0].checked = record.RSVPd;
        $("." + elems.eventNameLabel).text($("#" + elems.eventNameInput).val());
        $("." + elems.guestNameLabel).text(record.Name);
        $("#" + elems.rsvpGuestsInput).val(record.ReservedGuests);
        $("#" + elems.rsvpGuestsInput).attr('max', record.TotalInvited);
        if (record.RSVPd) {
            $("#" + elems.rsvpGuestsInput).show();
            $("#" + elems.rsvpGuestsInput).prev().show();
        } else {
            $("#" + elems.rsvpGuestsInput).hide().prev().hide();
        }
        $("#" + elems.rsvpModal).modal('show');
    }

   

    function FormatName(guest) {
        var ret = "";
        if (guest.Couple) {
            ret = guest.MaleFirstName + " & " + guest.FemaleFirstName;
        } else {
            ret = (guest.MaleFirstName ? guest.MaleFirstName : guest.FemaleFirstName);
        }
        ret += " " + guest.LastName;
        return ret;
    }

    function SwitchGiftType(giftType) {
        switch (giftType) {
            case "Check":
                $("#" + elems.GiftValueArea).show();
                $("#" + elems.CheckDepositDate).show();
                $("#" + elems.StoreBoughtInput).hide();
                $("#" + elems.GiftNameInput).hide();
                break;
            case "Cash":
                $("#" + elems.GiftValueArea).show();
                $("#" + elems.CheckDepositDate).hide();
                $("#" + elems.StoreBoughtInput).hide();
                $("#" + elems.GiftNameInput).hide();
                break;
            case "GiftItem":
                $("#" + elems.GiftValueArea).hide();
                $("#" + elems.CheckDepositDate).hide();
                $("#" + elems.StoreBoughtInput).show();
                $("#" + elems.GiftNameInput).show();
                break;
            default:
                break;
        }
    }

    function InitializeGiftModal(record) {
        selectedGiftRecord = record;
        console.log(record);
        $("#" + elems.GiftHeader).text(record.Name + '\'s ');
        if (record.GiftType != null) {
            $("#" + elems.DescriptionTextarea).val(record.Gift.Description);
            switch (record.GiftType) {                
                case "Check":
                    $("#" + elems.GiftTypeSelect)[0].selectedIndex = 0;
                    $("#" + elems.GiftValueArea).show();
                    $("#" + elems.CurrencyTypeSelect)[0].selectedIndex = record.Gift.Currency;
                    $("#" + elems.GiftValueInput).val(record.Gift.Amount);
                    $("#" + elems.CheckDepositDate).val(record.Gift.DepositDate);
                    break;
                case "Cash":
                    $("#" + elems.GiftTypeSelect)[0].selectedIndex = 1;
                    $("#" + elems.CurrencyTypeSelect)[0].selectedIndex = record.Gift.Currency;
                    console.log(record.Gift.Currency);
                    $("#" + elems.GiftValueInput).val(record.Gift.Amount);
                    $("#" + elems.CheckDepositDate).val(record.Gift.DepositDate);
                    break;
                case "GiftItem":
                    $("#" + elems.GiftTypeSelect)[0].selectedIndex = 2;
                    $("#" + elems.StoreBoughtInput).val(record.Gift.StoreBought);
                    $("#" + elems.GiftNameInput).val(record.Gift.Name);
                    break;
                default:
                    break;
            }
            SwitchGiftType(record.GiftType);
        } else {
            SwitchGiftType("Check");
        }
        $("#" + elems.giftModal).modal('show');
    }

    function FormatGiftDisplay(record) {
        switch (record.GiftType) {
            case "Check":
                return 'Check - ' + CurrencyHash[record.Gift.Currency].Symbol + record.Gift.Amount.toFixed(2);
            case "Cash":
                return 'Cash - ' + CurrencyHash[record.Gift.Currency].Symbol + record.Gift.Amount.toFixed(2);
            case "GiftItem":
                    return record.Gift.Name;
        }
    }

    $("#" + elems.UpdateGiftBtn).click(function () {
        $("#" + elems.GiftLoader).show();
        $.ajax({
            type: "POST",
            url: "Services/GuestsService.asmx/UpdateGift",
            data: JSON.stringify({
                'guestID': selectedGiftRecord.GuestID,
                'eventID': myeventID,
                'giftType': $("#" + elems.GiftTypeSelect).find("option:selected").val(),
                'description': $("#" + elems.DescriptionTextarea).val(),
                'amount': $("#" + elems.GiftValueInput).val(),
                'currency': $("#" + elems.CurrencyTypeSelect).find("option:selected").val(),
                'depositdate': $("#" + elems.CheckDepositDate).val(),
                'name': $("#" + elems.GiftNameInput).val(),
                'storebought' : $("#" + elems.StoreBoughtInput).val()
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d.Result == "OK") {
                    $("#" + elems.GiftLoader).hide();
                    $("#" + elems.giftModal).modal('hide');
                    UpdatePageAfterChange();
                } else {
                    $("#" + elems.GiftLoader).hide();
                    $("#" + elems.giftModal).modal('hide');
                    $("<div title='Server Error'>" + response.d.Message + "</div>").dialog({
                        modal: true,
                        buttons: {
                            Ok: function () {
                                $(this).dialog("close");
                            }
                        }
                    });
                }
            },
            error: function () {
            }
        });
        return false;  
    });

    $("#" + elems.GiftTypeSelect).change(function () {
        SwitchGiftType($(this).find("option:selected").val());
    });
    SwitchGiftType($("#" + elems.GiftTypeSelect).find("option:selected").val());
    
    $("#" + elems.DateOfEventInput).datepicker({
        dateFormat: "dd/mm/yy",
        showButtonPanel: true,
        changeYear: true,
    });

    $("#" + elems.CheckDepositDate).datepicker({
        dateFormat: "dd/mm/yy",
        showButtonPanel: true,
        changeYear: true
    });

    $("#" + elems.TimeOfEventInput).timeEntry({
        show24Hours: true,
        useMouseWheel: false,
        defaultTime: '19:30'
    }).text('19:30');

    $("#" + elems.AddGuestButton).click(function () {
        selectedGuest = $("#" + elems.GuestSearchBox).select2("data");
        $("." + elems.guestNameLabel).text(FormatName(selectedGuest));
        $("#" + elems.eventNameLabel).text($("#" + elems.eventNameInput).val());
        $("#" + elems.additionalGuestsInput).val('0');
        $("#" + elems.additionalGuestsInput).focus();   
        $("#" + elems.addNewGuestModal).modal('show');
        return false;
    });

    $("#" + elems.InviteGuestButton).click(function () {
        $("#" + elems.InviteGuestAjaxLoader).show();
        $.ajax({
            type: "POST",
            url: "Services/GuestsService.asmx/InviteGuestToEvent",
            data: JSON.stringify({
                'guestID': selectedGuest.ID,
                'eventID': myeventID,
                'additionalGuests' : parseInt($("#" + elems.additionalGuestsInput).val())
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                $("#" + elems.InviteGuestAjaxLoader).hide();
                $("#" + elems.addNewGuestModal).modal('hide');
                UpdatePageAfterChange();
            },
            error: function() {
            }
        });
        return false;
    });
    $("#" + elems.GuestSearchBox).select2({
        placeholder: "Search for guest to invite",
        minimumInputLength: 3,
        id: function (guest) { return { id: guest.id } },
        ajax: {
            url: "Services/GuestsService.asmx/SearchForNonInvitedGuests",
            dataType: "json",
            data: function (term, page) {
                return JSON.stringify({
                    keyword: term,
                    eventID : myeventID
                });
            },
            results: function (data, page) {
                return { results: JSON.parse(data.d) }
            },
            params: {
                contentType: "application/json; charset=utf-8",
                type: "POST"
            }
        },
        formatResult: function (guest) {
            return FormatName(guest) + " - " + guest.Email;
        },
        formatSelection: function (guest) {
            return FormatName(guest) + " - " + guest.Email;
        }
    });
    $("#" + elems.HallInput).select2();

    if ($("#" + elems.countdownRow).css('display') != 'none') {
        var endDate = $("#" + elems.startCount).data('date');
        $("#counter").countdown({
            date: endDate,
            render: function (data) {
                var html = [];
                if (data.years > 0) {
                    html.push(
                        "<div>",
                        this.leadingZeros(data.years, 2),
                        "<span>years</span></div>"
                     );
                }
                if (data.days > 0) {
                    html.push(
                        "<div>",
                        this.leadingZeros(data.days, 2),
                        "<span>days</span></div>"
                     );
                }
                html.push(
                    "<div>",
                        this.leadingZeros(data.hours, 2),
                        "<span>hrs</span></div>",
                        "<div>",
                        this.leadingZeros(data.min, 2),
                        "<span>min</span></div>",
                        "<div>",
                        this.leadingZeros(data.sec, 2),
                        "<span>sec</span></div>"
                    );
                $(this.el).html(html.join(""));
            }
        });
    }

   


    //JTABLE
    $("#" + elems.GuestsTable).jtable({
        title: 'Guest\'s Table',
        paging: true,
        pageSize: 10,
        sorting: true,
        defaultSorting: 'Name ASC',
        actions: {
            listAction: 'Services/GuestsService.asmx/JtableListEventsGuests'
        },
        fields: {
            GuestID: {
                key: true,
                list: false
            },
            Name: {
                title: 'Name',
                width: '30%',
                display: function (data) {
                    return '<a href="Guests.aspx#gid=' + data.record.GuestID + '" style="display:block;text-align:center">' + data.record.Name + '</a>';
                }
            },
            Email: {
                title: 'Email',
                width: '30%'
            },
            RSVP: {
                title: 'RSVPd',
                width: '16%',
                display: function (data) {
                    if (!data.record.RSVPd) {
                        return '<a href="#" class="rsvpbutton" style="color:red;display:block;text-align:center">Not Yet!</a>';
                    }
                    return '<a href="#" class="rsvpbutton" style="display:block;text-align:center">' + data.record.ReservedGuests + '</a>';
                }
            },
            Gift: {
                title: 'Gift',
                width: '24%',
                display: function (data) {
                    if (data.record.Gift == null) {
                        return '<a href="#" class="giftbutton" onclick="return false;" style="color:red;display:block;text-align:center">Not Yet!</a>';                        
                    }
                    else {
                        return '<a href="#" class="giftbutton" onclick="return false;" style="display:block;text-align:center">' + FormatGiftDisplay(data.record) + '</a>';
                    }
                }
            }


        },
        recordsLoaded: function (event, data) {
            $(".rsvpbutton").click(function () {
                var id = parseInt($(this).parent().parent().data('record-key'));
                InitializeRSVPModal($.grep(data.records, function (n, i) {
                    return n.GuestID == id;
                })[0]);
                return false;
            });
            $(".giftbutton").click(function () {
                var id = parseInt($(this).parent().parent().data('record-key'));
                InitializeGiftModal($.grep(data.records, function (n, i) {
                    return n.GuestID == id;
                })[0]);
                return false;
            });
        }
    });
    $("#" + elems.GuestsTable).jtable('load', { eventID: myeventID });

    $("#" + elems.rsvpCheckBox).click(function () {
        if (!$("#" + elems.rsvpModal).hasClass('in')) {
            return;
        }
        $("#" + elems.rsvpGuestsInput).toggle();
        $("#" + elems.rsvpGuestsInput).prev().toggle();
    });

    $("#" + elems.updateRsvpButton).click(function () {
        $("#" + elems.rsvpAjaxLoader).show();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "Services/GuestsService.asmx/RSVPGuestToEvent",
            data: JSON.stringify({
                eventID: myeventID,
                guestID: selectedRecord.GuestID,
                rsvp: $("#" + elems.rsvpCheckBox)[0].checked,
                numReserved: parseInt($("#" + elems.rsvpGuestsInput).val())
            }),
            success: function (response) {
                response = response.d;
                $("#" + elems.rsvpAjaxLoader).hide();
                if (response.Result == "OK") {
                    $("#" + elems.rsvpModal).modal('hide');
                }
                UpdatePageAfterChange();
            },
            error: function () {
                console.log('error');
            }
        });
        return false;
    });
};